<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Modbus数据采集系统 - 监控面板</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }
        
        .header p {
            opacity: 0.9;
        }
        
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 1rem;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #667eea;
        }
        
        .stat-card h3 {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        
        .stat-card .value {
            font-size: 2rem;
            font-weight: bold;
            color: #333;
        }
        
        .stat-card.online .value {
            color: #28a745;
        }
        
        .stat-card.warning .value {
            color: #ffc107;
        }
        
        .stat-card.error .value {
            color: #dc3545;
        }
        
        .data-section {
            background: white;
            border-radius: 8px;
            padding: 1.5rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .section-title {
            font-size: 1.5rem;
            color: #333;
        }
        
        .refresh-btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .refresh-btn:hover {
            background: #5a6fd8;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th,
        .data-table td {
            text-align: left;
            padding: 1rem;
            border-bottom: 1px solid #eee;
        }
        
        .data-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #555;
        }
        
        .data-table tr:hover {
            background-color: #f8f9fa;
        }
        
        .quality-good {
            color: #28a745;
            font-weight: bold;
        }
        
        .quality-bad {
            color: #dc3545;
            font-weight: bold;
        }
        
        .quality-uncertain {
            color: #ffc107;
            font-weight: bold;
        }
        
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 0.5rem;
        }
        
        .status-online {
            background-color: #28a745;
        }
        
        .status-offline {
            background-color: #dc3545;
        }
        
        .connection-status {
            position: fixed;
            top: 1rem;
            right: 1rem;
            background: white;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            border-left: 4px solid #28a745;
        }
        
        .connection-status.disconnected {
            border-left-color: #dc3545;
        }
        
        .loading {
            text-align: center;
            padding: 2rem;
            color: #666;
        }
        
        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 1rem;
            border-radius: 4px;
            margin: 1rem 0;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Modbus数据采集系统</h1>
        <p>实时监控和数据采集平台</p>
    </div>
    
    <div class="connection-status" id="connectionStatus">
        <span class="status-indicator status-offline"></span>
        <span id="connectionText">连接中...</span>
    </div>
    
    <div class="container">
        <!-- 统计信息 -->
        <div class="stats-grid">
            <div class="stat-card online">
                <h3>在线设备</h3>
                <div class="value" id="onlineDevices">--</div>
            </div>
            <div class="stat-card">
                <h3>数据点位</h3>
                <div class="value" id="totalPoints">--</div>
            </div>
            <div class="stat-card">
                <h3>采集频率</h3>
                <div class="value" id="collectionRate">-- Hz</div>
            </div>
            <div class="stat-card">
                <h3>内存使用</h3>
                <div class="value" id="memoryUsage">-- MB</div>
            </div>
        </div>
        
        <!-- 设备状态 -->
        <div class="data-section">
            <div class="section-header">
                <h2 class="section-title">设备状态</h2>
                <button class="refresh-btn" onclick="refreshDevices()">刷新</button>
            </div>
            <div id="devicesContent">
                <div class="loading">加载设备信息...</div>
            </div>
        </div>
        
        <!-- 实时数据 -->
        <div class="data-section">
            <div class="section-header">
                <h2 class="section-title">实时数据</h2>
                <button class="refresh-btn" onclick="refreshData()">刷新</button>
            </div>
            <div id="dataContent">
                <div class="loading">加载数据...</div>
            </div>
        </div>
    </div>
    
    <script>
        let ws = null;
        let reconnectInterval = null;
        
        // WebSocket连接
        function connectWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const wsUrl = `${protocol}//${window.location.host}/ws`;
            
            ws = new WebSocket(wsUrl);
            
            ws.onopen = function() {
                console.log('WebSocket连接已建立');
                updateConnectionStatus(true);
                if (reconnectInterval) {
                    clearInterval(reconnectInterval);
                    reconnectInterval = null;
                }
            };
            
            ws.onmessage = function(event) {
                try {
                    const message = JSON.parse(event.data);
                    handleWebSocketMessage(message);
                } catch (e) {
                    console.error('解析WebSocket消息失败:', e);
                }
            };
            
            ws.onclose = function() {
                console.log('WebSocket连接已关闭');
                updateConnectionStatus(false);
                // 自动重连
                if (!reconnectInterval) {
                    reconnectInterval = setInterval(connectWebSocket, 5000);
                }
            };
            
            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
                updateConnectionStatus(false);
            };
        }
        
        // 更新连接状态
        function updateConnectionStatus(connected) {
            const statusEl = document.getElementById('connectionStatus');
            const textEl = document.getElementById('connectionText');
            const indicator = statusEl.querySelector('.status-indicator');
            
            if (connected) {
                statusEl.classList.remove('disconnected');
                indicator.classList.remove('status-offline');
                indicator.classList.add('status-online');
                textEl.textContent = 'WebSocket已连接';
            } else {
                statusEl.classList.add('disconnected');
                indicator.classList.remove('status-online');
                indicator.classList.add('status-offline');
                textEl.textContent = 'WebSocket已断开';
            }
        }
        
        // 处理WebSocket消息
        function handleWebSocketMessage(message) {
            switch (message.type) {
                case 'data_update':
                    updateDataPoint(message.data);
                    break;
                case 'device_status':
                    updateDeviceStatus(message.status);
                    break;
                case 'system_status':
                    updateSystemStats(message.status);
                    break;
                default:
                    console.log('未知消息类型:', message.type);
            }
        }
        
        // 更新数据点
        function updateDataPoint(data) {
            const row = document.querySelector(`tr[data-point-id="${data.point_id}"]`);
            if (row) {
                row.querySelector('.value').textContent = data.value.toFixed(2);
                row.querySelector('.timestamp').textContent = formatTimestamp(data.timestamp);
                row.querySelector('.quality').textContent = data.quality;
                row.querySelector('.quality').className = `quality quality-${data.quality.toLowerCase()}`;
            }
        }
        
        // 更新设备状态
        function updateDeviceStatus(status) {
            const row = document.querySelector(`tr[data-device-id="${status.device_id}"]`);
            if (row) {
                const statusCell = row.querySelector('.device-status');
                statusCell.innerHTML = `
                    <span class="status-indicator ${status.online ? 'status-online' : 'status-offline'}"></span>
                    ${status.online ? '在线' : '离线'}
                `;
                row.querySelector('.last-comm').textContent = status.last_communication ? 
                    formatTimestamp(status.last_communication) : '从未通信';
            }
        }
        
        // 更新系统统计
        function updateSystemStats(status) {
            document.getElementById('onlineDevices').textContent = 
                status.collector ? status.collector.active_tasks : '--';
            document.getElementById('totalPoints').textContent = 
                status.storage ? status.storage.memory_points : '--';
            document.getElementById('memoryUsage').textContent = 
                status.storage ? status.storage.memory_usage_mb.toFixed(1) : '--';
        }
        
        // 格式化时间戳
        function formatTimestamp(timestamp) {
            return new Date(timestamp).toLocaleString('zh-CN');
        }
        
        // API请求函数
        async function apiRequest(url) {
            try {
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                return await response.json();
            } catch (error) {
                console.error(`API请求失败 ${url}:`, error);
                throw error;
            }
        }
        
        // 刷新设备信息
        async function refreshDevices() {
            try {
                const response = await apiRequest('/api/devices');
                if (response.success) {
                    renderDevices(response.data);
                } else {
                    showError('获取设备信息失败: ' + response.message);
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            }
        }
        
        // 渲染设备表格
        function renderDevices(devices) {
            const content = document.getElementById('devicesContent');
            
            if (devices.length === 0) {
                content.innerHTML = '<p class="loading">暂无设备数据</p>';
                return;
            }
            
            const table = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>设备ID</th>
                            <th>状态</th>
                            <th>最后通信</th>
                            <th>错误次数</th>
                            <th>最后错误</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${devices.map(device => `
                            <tr data-device-id="${device.device_id}">
                                <td>${device.device_id}</td>
                                <td class="device-status">
                                    <span class="status-indicator ${device.online ? 'status-online' : 'status-offline'}"></span>
                                    ${device.online ? '在线' : '离线'}
                                </td>
                                <td class="last-comm">${device.last_communication ? formatTimestamp(device.last_communication) : '从未通信'}</td>
                                <td>${device.error_count}</td>
                                <td>${device.last_error || '无'}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
            
            content.innerHTML = table;
        }
        
        // 刷新数据
        async function refreshData() {
            try {
                const response = await apiRequest('/api/points?page_size=50');
                if (response.success) {
                    renderDataPoints(response.data.items || response.data);
                } else {
                    showError('获取数据失败: ' + response.message);
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            }
        }
        
        // 渲染数据点表格
        function renderDataPoints(points) {
            const content = document.getElementById('dataContent');
            
            if (points.length === 0) {
                content.innerHTML = '<p class="loading">暂无数据</p>';
                return;
            }
            
            const table = `
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>点位ID</th>
                            <th>设备ID</th>
                            <th>名称</th>
                            <th>数值</th>
                            <th>质量</th>
                            <th>时间戳</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${points.map(point => `
                            <tr data-point-id="${point.point_id}">
                                <td>${point.point_id}</td>
                                <td>${point.device_id}</td>
                                <td>${point.name}</td>
                                <td class="value">${typeof point.value === 'number' ? point.value.toFixed(2) : point.value}</td>
                                <td class="quality quality-${point.quality.toLowerCase()}">${point.quality}</td>
                                <td class="timestamp">${formatTimestamp(point.timestamp)}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;
            
            content.innerHTML = table;
        }
        
        // 显示错误信息
        function showError(message) {
            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = message;
            
            const container = document.querySelector('.container');
            container.insertBefore(errorDiv, container.firstChild);
            
            setTimeout(() => {
                errorDiv.remove();
            }, 5000);
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 连接WebSocket
            connectWebSocket();
            
            // 初始加载数据
            refreshDevices();
            refreshData();
            
            // 定期刷新数据
            setInterval(refreshData, 30000); // 30秒刷新一次
            setInterval(refreshDevices, 60000); // 60秒刷新一次
        });
    </script>
</body>
</html>